// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ReflectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.util.ContextHolder;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.entity.FbaShipment;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.FbaShipmentMapper;
import com.fowo.api.mapper.FbaShipmentProductMapper;
import com.fowo.api.mapper.FbaShipmenttrackMapper;
import com.fowo.api.model.fba.shipment.FbaShipmentAgainPairAction;
import com.fowo.api.model.fba.shipment.FbaShipmentItemVo;
import com.fowo.api.model.fba.shipment.FbaShipmentSearchParamPo;
import com.fowo.api.model.fba.shipment.FbaShipmentVo;
import com.fowo.api.model.fba.shipment.product.FbaShipmentProductItemVo;
import com.fowo.api.model.fba.shipment.product.FbaShipmentProductItemVoPages;
import com.fowo.api.model.fba.shipment.product.FbaShipmentProductSearchParamPo;
import com.fowo.api.model.fba.shipmenttrack.FbaShipmenttrackSearchParamPo;
import com.fowo.api.service.FbaShipmentProductService;
import com.fowo.api.service.FbaShipmentService;
import com.fowo.api.service.FbaShipmenttrackService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.sys.model.NewSerialRequest;
import com.fowo.api.sys.service.SysSerialService;
import com.fowo.api.user.model.JwtUserInfo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * fba货件 服务实现基类
 * @author 蜂窝蜜造平台 配置人：李玉娇，沈友谅
 */
@Slf4j
@DataObjectType(FbaShipment.class)
@DS("ds24")
public class FbaShipmentBaseServiceImpl
  extends ServiceImpl<FbaShipmentMapper, FbaShipment>
  implements FbaShipmentService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("createUserName", "su.`name`");
      put("shopShopName", "si.`shop_name`");
      put("sendAddressAlias", "fbaa.`alias`");
    }
  };

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected FbaShipmentService self;

  @Resource
  protected FbaShipmenttrackService fbaShipmenttrackService;

  @Resource
  protected FbaShipmentProductService fbaShipmentProductService;

  @Resource
  protected SysSerialService sysSerialService;

  @Resource
  protected WorkFlowService workFlowService;

  @Autowired(required = false)
  protected FbaShipmentAgainPairAction fbaShipmentAgainPairAction;

  @Resource
  protected Validator validator;

  /**
   * 创建fba货件
   * @param model fba货件
   * @return 新数据的主键
   */
  @DataActivity(action = SysDataActivityAction.Add)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(FbaShipmentVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    FbaShipment entity = new FbaShipment();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }

    if (model.getLabelType() == null) {
      entity.setLabelType("SELLER_LABEL");
    }

    if (model.getPackingType() == null) {
      entity.setPackingType("1");
    }

    if (model.getShipmenttype() == null) {
      entity.setShipmenttype("SP");
    }
    // 填充序列号
    if (!StringUtils.hasText(entity.getShipmentId())) {
      entity.setShipmentId(
        sysSerialService.getNewSerial(
          new NewSerialRequest(null, "FbaShipment.shipmentId")
        )
      );
    }
    if (this.save(entity)) {
      model.setId(entity.getId());
      updateAllChilds(model);
      return entity.getId();
    }
    throw new Exception("fba货件保存失败");
  }

  /**
   * 更新所有子表
   * @param model fba货件
   */
  protected void updateAllChilds(FbaShipmentVo model) throws Exception {
    if (model.getTrackno() != null) {
      fbaShipmenttrackService.saveAllByParentId(
        model.getId(),
        model.getTrackno()
      );
    }

    if (model.getList() != null) {
      fbaShipmentProductService.saveAllByParentFbaShipment(
        model.getId(),
        model.getList()
      );
    }
  }

  /**
   * 更新fba货件
   * @param model fba货件
   * @return 更新是否成功
   */
  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(FbaShipmentVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    FbaShipment entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("fba货件不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "createTime",
      "createUser",
      "lastUpdateTime",
      "lastUpdateUser",
      "shipmentId"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      updateAllChilds(model);
      return true;
    }
    return false;
  }/**
   * 更新fba货件（带空值）
   * @param model fba货件
   * @return 更新是否成功
   */

  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(FbaShipmentVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    FbaShipment entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("fba货件不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(FbaShipment::getLastUpdateTime, model.getLastUpdateTime())
      .set(FbaShipment::getLastUpdateUser, model.getLastUpdateUser())
      .set(FbaShipment::getShop, model.getShop())
      .set(FbaShipment::getSendAddress, model.getSendAddress())
      .set(
        FbaShipment::getFactoryDirectDelivery,
        model.getFactoryDirectDelivery()
      )
      .set(FbaShipment::getLabelType, model.getLabelType())
      .set(FbaShipment::getShipmentName, model.getShipmentName())
      .set(FbaShipment::getPackingType, model.getPackingType())
      .set(FbaShipment::getConsignerName, model.getConsignerName())
      .set(FbaShipment::getPhone, model.getPhone())
      .set(FbaShipment::getShipmentsCountry, model.getShipmentsCountry())
      .set(FbaShipment::getStreetAddress, model.getStreetAddress())
      .set(FbaShipment::getStreetAddress2, model.getStreetAddress2())
      .set(FbaShipment::getCity, model.getCity())
      .set(FbaShipment::getCounty, model.getCounty())
      .set(FbaShipment::getProvince, model.getProvince())
      .set(FbaShipment::getPostcode, model.getPostcode())
      .set(FbaShipment::getRemark, model.getRemark())
      .set(FbaShipment::getShippingAddress, model.getShippingAddress())
      .set(FbaShipment::getShipmenttype, model.getShipmenttype())
      .set(FbaShipment::getCarrier, model.getCarrier())
      .set(FbaShipment::getTransportmethod, model.getTransportmethod())
      .set(
        FbaShipment::getPackinguploadchannel,
        model.getPackinguploadchannel()
      )
      .eq(FbaShipment::getId, model.getId())
      .update();
    if (isOk) {
      updateAllChilds(model);
    }
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(FbaShipmentSearchParamPo search) {
    return false;
  }

  /**
   * 批量删除指定主键列表关联的所有子表数据(此方法不包括事务，必须由其它已包括事务的方法调用)
   */
  protected void batchDeleteChilds(List<Long> ids) throws Exception {
    // 处理子表字段 跟踪号(trackno) 对应的对象
    FbaShipmenttrackSearchParamPo tracknoSearchParam =
      new FbaShipmenttrackSearchParamPo();
    tracknoSearchParam.setDisableDataPremissions(true);
    tracknoSearchParam.setParentIdInList(ids);
    FbaShipmenttrackMapper localFbaShipmenttrackMapper = ContextHolder
      .getApplicationContext()
      .getBean(FbaShipmenttrackMapper.class);
    tracknoSearchParam.applySqlSegments();
    List<Long> tracknoIdList = localFbaShipmenttrackMapper.searchIds(
      tracknoSearchParam
    );
    if (!tracknoIdList.isEmpty()) {
      FbaShipmenttrackService localFbaShipmenttrackService = ContextHolder
        .getApplicationContext()
        .getBean(FbaShipmenttrackService.class);
      localFbaShipmenttrackService.batchDelete(tracknoIdList);
    }

    // 处理子表字段 子表(list) 对应的对象
    FbaShipmentProductSearchParamPo listSearchParam =
      new FbaShipmentProductSearchParamPo();
    listSearchParam.setDisableDataPremissions(true);
    listSearchParam.setParentFbaShipmentInList(ids);
    FbaShipmentProductMapper localFbaShipmentProductMapper = ContextHolder
      .getApplicationContext()
      .getBean(FbaShipmentProductMapper.class);
    listSearchParam.applySqlSegments();
    List<Long> listIdList = localFbaShipmentProductMapper.searchIds(
      listSearchParam
    );
    if (!listIdList.isEmpty()) {
      FbaShipmentProductService localFbaShipmentProductService = ContextHolder
        .getApplicationContext()
        .getBean(FbaShipmentProductService.class);
      localFbaShipmentProductService.batchDelete(listIdList);
    }
  }

  /**
   * 删除fba货件
   * @param id fba货件的主键
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean delete(Long id) throws Exception {
    batchDeleteChilds(Collections.singletonList(id));
    return this.removeById(id);
  }

  /**
   * 批量删除fba货件
   * @param ids fba货件的主键列表
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    batchDeleteChilds(ids);

    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 通过货件名称查询fba货件主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByShipmentName(String shipmentName) {
    return this.baseMapper.getIdByShipmentName(shipmentName);
  }

  /**
   * 通过货件名称查询fba货件多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByShipmentName(List<String> list) {
    return this.baseMapper.getIdsByShipmentName(list);
  }

  /**
   * 通过fba货件主键查询货件名称
   */
  @Override
  public String getShipmentNameById(Long id) {
    return this.baseMapper.getShipmentNameById(id);
  }

  /**
   * 通过fba货件主键查询货件名称列表
   */
  @Override
  public List<String> getShipmentNameByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getShipmentNameByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (String) stringObjectMap.get("shipmentName"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id fba货件的主键
   */
  @DataActivity(action = SysDataActivityAction.View)
  @Override
  public FbaShipmentVo getVoById(Long id) throws Exception {
    FbaShipmentVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }

    FbaShipmenttrackSearchParamPo tracknoSearchParamPo =
      new FbaShipmenttrackSearchParamPo();
    tracknoSearchParamPo.setParentId(id);
    tracknoSearchParamPo.getExtendData().put("queryMode", "sub");
    tracknoSearchParamPo.getExtendData().put("queryParent", "FbaShipment");
    tracknoSearchParamPo.applySqlSegments();
    vo.setTrackno(fbaShipmenttrackService.search(tracknoSearchParamPo));

    FbaShipmentProductSearchParamPo listSearchParamPo =
      new FbaShipmentProductSearchParamPo();
    listSearchParamPo.setParentFbaShipment(id);
    listSearchParamPo.getExtendData().put("queryMode", "sub");
    listSearchParamPo.getExtendData().put("queryParent", "FbaShipment");
    listSearchParamPo.applySqlSegments();
    vo.setList(fbaShipmentProductService.search(listSearchParamPo));

    return vo;
  }

  /**
   * 分页查询fba货件
   * @param search 查询条件
   * @return fba货件分页查询结果
   */
  @Override
  public Page<FbaShipmentItemVo> pageSearch(FbaShipmentSearchParamPo search) {
    Page<FbaShipmentItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(FbaShipmentItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 通用方法，为列表添加子表数据
   * @param pageResult 列表结果
   */
  protected Page<?> appendWithChild(Page<FbaShipmentItemVo> pageResult) {
    return appendWithChild(pageResult, null);
  }

  /**
   * 通用方法，为列表添加子表数据
   * @param pageResult 列表结果
   * @param sort 子表排序
   */
  protected Page<?> appendWithChild(
    Page<FbaShipmentItemVo> pageResult,
    String sort
  ) {
    if (
      pageResult == null ||
      pageResult.getRecords() == null ||
      pageResult.getRecords().isEmpty()
    ) {
      return pageResult;
    }
    Page<JSONObject> withChildPage = new Page<>(
      pageResult.getCurrent(),
      pageResult.getSize(),
      pageResult.getTotal()
    );
    withChildPage.setRecords(new ArrayList<>());

    FbaShipmentProductSearchParamPo listSearchParamPo =
      new FbaShipmentProductSearchParamPo();
    listSearchParamPo.setSort(sort);
    listSearchParamPo.setPageSize(200);
    listSearchParamPo.setParentFbaShipmentInList(
      pageResult
        .getRecords()
        .stream()
        .map(FbaShipmentItemVo::getId)
        .collect(Collectors.toList())
    );

    Map<String, Page<FbaShipmentProductItemVoPages>> listMaps =
      fbaShipmentProductService.pagesByParentFbaShipment(listSearchParamPo);

    for (FbaShipmentItemVo itemVo : pageResult.getRecords()) {
      JSONObject itemJson = (JSONObject) JSONObject.toJSON(itemVo);
      itemJson.put("list", listMaps.get(itemVo.getId().toString()));
      withChildPage.getRecords().add(itemJson);
    }
    return withChildPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return fba货件分页查询结果
   */
  @Override
  public Page<?> pageWithChildSearch(FbaShipmentSearchParamPo search) {
    return appendWithChild(pageSearch(search), search.toChildSort("list"));
  }

  /**
   * 仅获取子表的查询结果
   * @param parentId 主表编号
   * @param search 查询条件(仅使用分页参数，不处理其它条件)
   * @return
   */
  @Override
  public Page<?> pageOnlyChildSearch(
    Long parentId,
    FbaShipmentSearchParamPo search
  ) {
    FbaShipmentSearchParamPo parentSearchParam = new FbaShipmentSearchParamPo();
    parentSearchParam.setIdEq(parentId);
    List<FbaShipmentItemVo> parentList = search(parentSearchParam);
    if (parentList.size() > 0) {
      FbaShipmentItemVo itemVo = parentList.get(0);

      FbaShipmentProductSearchParamPo listSearchParamPo =
        new FbaShipmentProductSearchParamPo();
      listSearchParamPo.setPageSize(search.getPageSize());
      listSearchParamPo.setCurrent(search.getCurrent());
      listSearchParamPo.setParentFbaShipment(itemVo.getId());
      return fbaShipmentProductService.pageSearch(listSearchParamPo);
    } else {
      return null;
    }
  }

  /**
   * fba货件快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'FbaShipmentOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<FbaShipmentItemVo>> searchOptions(
    FbaShipmentSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询fba货件
   * @param search 查询条件
   * @return fba货件列表查询结果
   */
  @Override
  public List<FbaShipmentItemVo> search(FbaShipmentSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询fba货件最后更新时间
   * @param search 查询条件
   * @return fba货件最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(FbaShipmentSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 重新配对SKU
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了重新配对SKU操作"
  )
  @Override
  public void againPair(List<Long> ids) throws Exception {
    if (fbaShipmentAgainPairAction == null) {
      throw new Exception("此操作当前不可用");
    }
    fbaShipmentAgainPairAction.run(ids);
  }

  /**
   * 全部
   */
  @Override
  public List<FbaShipmentItemVo> allData(FbaShipmentSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.allData(search);
  }

  /**
   * 全部分页
   */
  @Override
  public Page<FbaShipmentItemVo> allDataPage(FbaShipmentSearchParamPo search) {
    Page<FbaShipmentItemVo> allDataPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return allDataPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return allDataPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    allDataPage =
      this.baseMapper.allDataPage(
          search.toPage(this.baseMapper.allDataCount(search)),
          search
        );
    List<Long> recordIds = allDataPage
      .getRecords()
      .stream()
      .map(FbaShipmentItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return allDataPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return allDataPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    allDataPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return allDataPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return fba货件分页查询结果
   */
  @Override
  public Page<?> allDataPageWithChildSearch(FbaShipmentSearchParamPo search) {
    return appendWithChild(allDataPage(search), search.toChildSort("list"));
  }

  /**
   * 查询全部最后更新时间
   * @param search 查询条件
   * @return 全部最后更新时间
   */
  @Override
  public Date allDataLastUpdateTime(FbaShipmentSearchParamPo search) {
    return this.baseMapper.allDataLastUpdateTime(search);
  }
}
